<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="rw.ac.kiosc.jdbc.school.School" %>
<%@page import="rw.ac.kiosc.jdbc.school.orm.User" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%
        School school = new School();
        User user = null;
        String userIp = (String) session.getAttribute("userIp");
        int id = 0;
        String userId = (String) session.getAttribute("userId");
        if (userIp != null && userId != null) {
            try {
                id = Integer.parseInt(userId);
            } catch (Exception ex) {
            }
            if (userIp.equals(request.getRemoteAddr())) {
                user = school.getUserDAO().getUserById(id);
                if (user != null) {
                    response.sendRedirect("home.htm");
                }
            }
        }
        String state = "";
        if ("POST".equals(request.getMethod())) {
            user = school.authenticateUser(request.getParameter("username"), request.getParameter("password"));
            if (user != null) {
                session = request.getSession(true);
                session.setAttribute("userId", "" + user.getUserId());
                session.setAttribute("userIp", request.getRemoteAddr());
                response.sendRedirect("home.htm");
                state = "OK";
            } else {
                state = "ERROR";
            }
        }
%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>KIOSC School Login</title>
    </head>
    <body>
        <h4>Please login to our School system</h4>
        <hr>
        <%if (state == "ERROR") {
        %>
        <span style = "color:red" > <b>Invalid Username/password combination, please try again</b></span>
        <%        }
        %>
        <form action="login.htm" method="post">
            <table cellpadding="5" cellspacing="5" bgcolor="gray">
                <tr>
                    <td align="right"><b>Username</b></td>
                    <td align="left"><input type="text" size="10" maxlength="50" name="username" id="username"/></td>
                </tr>
                <tr>
                    <td align="right"><b>Password</b></td>
                    <td align="left"><input type="password" size="10" maxlength="50" name="password" id="password"/></td>
                </tr>
                <tr>
                    <td align="right">&nbsp;</td>
                    <td align="left"><input type="submit" value="  Login  "/></td>
                </tr>
            </table>
        </form>
    </body>
</html>
